const path = require("path");
export async function UploadFiles() {
    const ftp = require("basic-ftp");
    const fs = require("fs");
    const json5 = require("json5");
    const ftpConfig = json5.parse(
        fs.readFileSync("./ftp.config", { encoding: "utf-8" })
    );
    const client = new ftp.Client();
    client.ftp.verbose = true;
    try {
        await client.access(ftpConfig.uploadconfig.ftpConnectConfig);
        // ignore files
        const fileList = await client.list(ftpConfig.uploadconfig.remotePath);
        for(const filePath of fileList){
            if(filePath.isDirectory){
                const currentDir = path.join(ftpConfig.uploadconfig.remotePath, filePath.name);
                const isExist = InPathList(ftpConfig.uploadconfig.ignoreList, filePath.name);
                if(!isExist){
                    await client.ensureDir(currentDir);
                    await client.clearWorkingDir();
                }
            }
        }
        await client.ensureDir(ftpConfig.uploadconfig.remotePath);
        await client.uploadFromDir(ftpConfig.uploadconfig.uploadPath);
    }
    catch(err) {
        console.log(err);
        return false;
    }
    finally {
        client.close();
    }

    return true;
}

function InPathList(list: string[], targetPath: string) {
    for(const filepath of list){
        const joinPath = path.join(filepath);
        targetPath = path.join(targetPath);
        if(joinPath.toLowerCase() == targetPath.toLowerCase()){
            return true;
        }
    }
}
